#!/usr/bin/env node

var width = 960 - 1,
    height = 500 - 1,
    projectionName = process.argv[2],
    projectionSymbol = "geo" + projectionName[0].toUpperCase() + projectionName.slice(1);

if (!/^[a-z0-9]+$/i.test(projectionName)) throw new Error;

var topojson = require("topojson-client"),
    d3 = Object.assign({}, require("d3-format"), require("d3-geo"), require("../"));

var formatNumber = d3.format(".6");

var projection = d3[projectionSymbol]()
    .precision(0.01)
    .scale(1)
    .translate([0, 0])
    .center([0, 0]);

if (projection.rotate) projection.rotate([0, 0]);

var land = {type: "Sphere"};

switch (projectionName) {
  case "airy":
  case "chamberlin": {
    projection.clipAngle(90);
    break;
  }
  case "littrow": {
    land = d3.geoGraticule().extent([[-90, -60], [90, 60]]).outline();
    break;
  }
  case "modifiedStereographicAlaska": {
    var us = require("us-atlas/us/10m.json");
    land = topojson.feature(us, us.objects.states.geometries.filter(function(d) { return d.id === 2; })[0]);
    break;
  }
  case "modifiedStereographicGs48": {
    var us = require("us-atlas/us/10m.json");
    land = topojson.feature(us, {type: "GeometryCollection", geometries: us.objects.states.geometries.filter(function(d) { return d.id !== 2 && d.id !== 15 && d.id <= 56; })});
    break;
  }
  case "modifiedStereographicGs50": {
    land = d3.geoGraticule().extent([[-180, 15], [-50, 75]]).outline();
    break;
  }
  case "modifiedStereographicMiller": {
    land = d3.geoGraticule().extent([[-40, -40], [80, 80]]).outline();
    break;
  }
}

var path = d3.geoPath()
    .projection(projection);

var bounds = path.bounds(land),
    dx = bounds[1][0] - bounds[0][0],
    dy = bounds[1][1] - bounds[0][1],
    cx = (bounds[1][0] + bounds[0][0]) / 2,
    cy = (bounds[1][1] + bounds[0][1]) / 2,
    scale = Math.min(width / dx, height / dy);

console.log(`d3.${projectionSymbol}()
    .scale(${formatNumber(scale)})
    .center([${(projection.invert ? projection.invert([cx, cy]) : [0, 0]).map(formatNumber).join(", ")}]);
`);
